//导入数据库操作模块
const db = require('../db/index.js')
//导入全局配置文件
const config = require('../config')
//导入用户路由处理函数模块
const fileUtils = require('../utils/file.js')
const { result } = require('lodash')

//获取用户基本信息的处理函数
exports.getUserInfo = (req, res) => {
    // 定义查询语句，查询用户信息
    const sql = `SELECT userId, username, realname, avatar, description FROM users WHERE userId = ?`

    db.query(sql, req.user.userId, (err, results) => {
        // 查询出错
        if (err) {
            return res.cc(err) // 使用 res.cc 方法返回错误信息
        }
        // 如果没有找到用户
        if (results.length !== 1) {
            return res.cc('获取用户基本信息失败！') // 如果没有找到用户，返回错误信息
        }

        let handleUserInfo = results[0]
        handleUserInfo.avatar = `${config.host}:${config.port}` + results[0].avatar
        // 成功获取用户信息
        res.send({
            code: 200,
            message: '获取用户信息成功!',
            data: handleUserInfo, // 返回用户信息
        })
    })
}

//更改好友聊天页的可见状态
exports.setChatStatus = (req, res) => {
    const sql = `UPDATE conversations c SET c.if_userId1_close = '1', c.if_userId2_close = '1' WHERE
    c.conversation_id = ${req.body.conversation_id}`

    db.query(sql, (err, _result) => {
        if (err) {
            return res.cc(err)
        }

        res.send({
            code: 200,
            message: '更改好友聊天页可见状态成功',
        })
    })
}

//获取用户聊天好友信息的处理函数
exports.getChatListFriends = (req, res) => {
    //定义查询语句，查询聊天好友信息
    const sql = `SELECT u.userId, u.username, u.avatar, u.realname, c.conversation_id FROM users u
    JOIN friendships f ON (f.userId1 = u.userId OR f.userId2 = u.userId) JOIN conversations c
    ON ((c.userId1 = f.userId1 AND c.userId2 = f.userId2 AND c.if_userId1_close != 1) OR
    (c.userId1 = f.userId2 AND c.userId2 = f.userId1 AND c.if_userId2_close != 1)) WHERE
    (f.userId1 = ? OR f.userId2 = ?) AND u.userId != ?`

    // 执行查询操作
    db.query(sql, [req.user.userId, req.user.userId, req.user.userId], (err, results) => {
        // 如果查询出错，使用 res.cc 返回错误信息
        if (err) {
            return res.cc(err)
        }

        // 处理头像路径
        results.forEach((result) => {
            result.avatar = `${config.host}:${config.port}` + result.avatar
        })

        // 如果查询成功，返回聊天好友信息
        res.send({
            code: 200,
            message: '获取好友信息成功',
            data: results,
        })
    })
}

//获取用户好友信息的处理函数
exports.getUserFriends = (req, res) => {
    //定义查询语句，查询好友信息
    const sql = `SELECT u.userId, u.username, u.avatar, u.realname, c.conversation_id FROM users u
    JOIN friendships f ON (f.userId1 = u.userId OR f.userId2 = u.userId) JOIN conversations c ON
    ((c.userId1 = f.userId1 AND c.userId2 = f.userId2) OR (c.userId1 = f.userId2 AND c.userId2 = f.userId1 ))
    WHERE (f.userId1 = ? OR f.userId2 = ?) AND f.status = 'accept' AND u.userId != ?`

    // 执行查询操作
    db.query(sql, [req.user.userId, req.user.userId, req.user.userId], (err, results) => {
        // 如果查询出错，使用 res.cc 返回错误信息
        if (err) {
            return res.cc(err)
        }

        // 处理头像路径
        results.forEach((result) => {
            result.avatar = `${config.host}:${config.port}` + result.avatar
        })

        // 按照用户名称进行字典排序
        const sortedFriends = results.sort((a, b) => {
            // 使用 localeCompare 来进行字典顺序比较
            return a.realname.localeCompare(b.realname)
        })

        // 如果查询成功，返回好友信息
        res.send({
            code: 200,
            message: '获取好友信息成功',
            data: sortedFriends,
        })
    })
}

// 获取好友聊天记录的处理函数
exports.getChatHistory = (req, res) => {
    // 定义查询语句来获取聊天记录
    const sql = `SELECT c.conversation_id, c.userId1, c.userId2, c.unRead1, c.unRead2, m.message_id,
    m.sender_id, m.message_content, m.send_time, m.message_type, m.media_url, m.duration, m.media_size,
    m.preview_url, m.file_width, m.file_height FROM conversations c LEFT JOIN messages m ON c.conversation_id
    = m.conversation_id WHERE (c.userId1 = ? OR c.userId2 = ?)`

    // 执行 SQL 查询
    db.query(sql, [req.user.userId, req.user.userId], (err, results) => {
        // 如果查询出错，返回错误信息
        if (err) {
            return res.cc(err)
        }

        // 按照 conversation_id 分组聊天记录
        const chatHistory = results.reduce((acc, result) => {
            const {
                conversation_id,
                message_id,
                sender_id,
                message_content,
                send_time,
                message_type,
                media_url,
                duration,
                media_size,
                preview_url,
                file_width,
                file_height,
                userId1,
                userId2,
                unRead1,
                unRead2,
            } = result

            if (!acc[conversation_id]) {
                acc[conversation_id] = {
                    conversation_id: conversation_id,
                    users: [userId1, userId2],
                    unRead1: unRead1,
                    unRead2: unRead2,
                    messages: [],
                }
            }

            // 仅在有消息的情况下才推入 messages 数组
            if (message_id) {
                acc[conversation_id].messages.push({
                    message_id,
                    sender_id,
                    message_content,
                    send_time,
                    message_type,
                    media_url: `${config.host}:${config.port}${media_url}`,
                    duration,
                    media_size,
                    preview_url: `${config.host}:${config.port}${preview_url}`,
                    file_width,
                    file_height,
                })
            }

            return acc
        }, {})

        // 成功时返回聊天记录数组
        res.send({
            code: 200,
            message: '获取聊天记录成功',
            data: Object.values(chatHistory),
        })
    })
}

//处理用户发送消息的处理函数
exports.sendMessage = (req, res) => {
    //获取客户端提交到服务器的聊天记录
    const message = req.body
    //对表单数据进行合法性校验
    if (
        !message.conversation_id ||
        !message.sender_id ||
        !message.receiver_id ||
        !message.message_content ||
        !message.send_time ||
        !message.message_type
    ) {
        return res.cc('发送消息请求数据不全')
    }
    if (message.convasation_id < 0) {
        return res.cc('客户端发送了错误的消息')
    }
    if (message.media) {
        fileUtils.saveFileToDir(message.media_url, message.media)
    }
    let previewImgUrl
    if (message.message_type === 'video') {
        previewImgUrl = `/chatAppServer/picture/preview-${message.send_time}.png`
        fileUtils.saveFileToDir(previewImgUrl, message.preview_url.split(',')[1])
    }

    //定义储存聊天记录的sql语句
    const sql = 'insert into messages SET ?'
    db.query(
        sql,
        {
            conversation_id: message.conversation_id,
            sender_id: message.sender_id,
            message_content: message.message_content,
            send_time: message.send_time,
            message_type: message.message_type,
            media_url: message.media_url,
            duration: message.duration,
            media_size: message.media_size,
            preview_url: previewImgUrl,
            file_width: message.file_width,
            file_height: message.file_height,
        },
        (err, results) => {
            // 执行 SQL 语句失败
            if (err) {
                return res.cc(err)
            }
            //SQL语句执行成功，但影响行数不为1
            if (results.affectedRows !== 1) {
                return res.cc('消息发送失败，请稍后再试!')
            }

            let unReadSql
            if (message.sender_id < message.receiver_id) {
                unReadSql = `update conversations SET unRead2=
                unRead2 + 1 WHERE conversation_id=?`
            } else {
                unReadSql = `update conversations SET unRead1=
                unRead1 + 1 WHERE conversation_id=?`
            }

            db.query(unReadSql, message.conversation_id, (err, result) => {
                // 执行 SQL 语句失败
                if (err) {
                    return res.cc(err)
                }
                //SQL语句执行成功，但影响行数不为1
                if (results.affectedRows !== 1) {
                    return res.cc('未读信息数据更新失败，请稍后再试！')
                }

                // 消息发送成功
                res.cc('消息发送成功', 200)
            })
        },
    )
}

// 处理更新未读消息数量
exports.updateUnRead = (req, res) => {
    const updateFormData = req.body
    if (!updateFormData.conversation_id) {
        return res.cc('缺少会话id，无法更新未读信息数量')
    }
    let updateSql
    if (updateFormData.unRead1 === 0) {
        updateSql = 'update conversations set unRead1=? WHERE conversation_id=?'
    }
    if (updateFormData.unRead2 === 0) {
        updateSql = 'update conversations set unRead2=? WHERE conversation_id=?'
    }
    db.query(updateSql, [0, updateFormData.conversation_id], (err, result) => {
        // 执行 SQL 语句失败
        if (err) {
            return res.cc(err)
        }
        //SQL语句执行成功，但影响行数不为1
        if (result.affectedRows !== 1) {
            return res.cc('未读信息数量修改失败!')
        }
        res.cc('未读信息数量修改成功')
    })
}

// 获取用户好友请求信息
exports.getFriendRequire = (req, res) => {
    const userId = req.user.userId

    const sql = `SELECT 
    f.id AS friendshipId,
    f.status,
    f.initiator,
    CASE
      WHEN f.userId1 = ${userId} THEN f.userId2
      WHEN f.userId2 = ${userId} THEN f.userId1
    END AS friendId,
    u.avatar AS friendAvatar,
    u.username AS friendUsername,
    u.realname AS friendRealname
  FROM 
    friendships f
  JOIN 
    users u ON (f.userId1 = u.userId OR f.userId2 = u.userId) AND u.userId != ${userId}
  WHERE 
    (f.userId1 = ${userId} OR f.userId2 = ${userId})
    AND f.status IN ('verifying', 'accept', 'refuse')`

    // 执行查询操作
    db.query(sql, (err, results) => {
        // 如果查询出错，使用 res.cc 返回错误信息
        if (err) {
            return res.cc(err)
        }

        results.forEach((item) => {
            item.friendAvatar = `${config.host}:${config.port}` + item.friendAvatar
        })

        // 如果查询成功，返回好友申请信息
        res.send({
            code: 200,
            message: '获取好友申请信息成功',
            data: results,
        })
    })
}

//验证好友申请
exports.verifyRequire = (req, res) => {
    const verifyFormData = req.body
    const sql = `update friendships SET status='${verifyFormData.newStatus}' WHERE id=${verifyFormData.friendshipId}`

    db.query(sql, (err, _result) => {
        if (err) {
            return res.cc(err)
        }
        if (verifyFormData.newStatus === 'accept') {
            const addConSql = `Insert into conversations SET ?`
            let userId1, userId2

            if (verifyFormData.userId < verifyFormData.friendId) {
                userId1 = verifyFormData.userId
                userId2 = verifyFormData.friendId
            } else {
                userId1 = verifyFormData.friendId
                userId2 = verifyFormData.userId
            }

            db.query(
                addConSql,
                {
                    userId1: userId1,
                    userId2: userId2,
                    created_at: Date.now(),
                },
                (err, _result) => {
                    if (err) {
                        console.log(err)
                        return res.cc(err)
                    }

                    return res.send({
                        code: 200,
                        message: '已验证好友申请',
                    })
                },
            )
            return
        }

        return res.send({
            code: 200,
            message: '已验证好友申请',
        })
    })
}

//查找用户
exports.searchUser = (req, res) => {
    const searchForm = req.body

    const searchSql = `SELECT userId, username, avatar, description, realname from users WHERE username='${searchForm.searchUsername}'`

    db.query(searchSql, (err, results) => {
        // 查询出错
        if (err) {
            return res.cc(err) // 使用 res.cc 方法返回错误信息
        }
        // 如果没有找到用户
        if (results.length !== 1) {
            return res.cc('没有找到该用户！') // 如果没有找到用户，返回错误信息
        }

        let handleUserInfo = results[0]
        const resultUserId = handleUserInfo.userId
        handleUserInfo.avatar = `${config.host}:${config.port}` + results[0].avatar

        if (searchForm.userId === resultUserId) {
            // 成功获取用户信息
            return res.send({
                code: 200,
                message: '获取用户信息成功!',
                data: {
                    userInfo: handleUserInfo,
                }, // 返回用户信息
            })
        }

        const friendshipQuery = `SELECT status, initiator FROM friendships WHERE (userId1 = ? AND userId2 = ?) 
            OR (userId1 = ? AND userId2 = ?)`

        db.query(
            friendshipQuery,
            [searchForm.userId, resultUserId, resultUserId, searchForm.userId],
            (err, results) => {
                // 查询出错
                if (err) {
                    return res.cc(err) // 使用 res.cc 方法返回错误信息
                }

                let contactStatus = {
                    isContact: false,
                    status: null,
                    initiator: null,
                }

                if (results.length === 0) {
                    // 成功获取用户信息
                    return res.send({
                        code: 200,
                        message: '获取用户信息成功!',
                        data: {
                            userInfo: handleUserInfo,
                            contactStatus: contactStatus,
                        }, // 返回用户信息
                    })
                }

                if (results.length > 0) {
                    contactStatus = {
                        isContact: true,
                        status: results[0].status,
                        initiator: results[0].initiator,
                    }

                    // 成功获取用户信息
                    return res.send({
                        code: 200,
                        message: '获取用户信息成功!',
                        data: {
                            userInfo: handleUserInfo,
                            contactStatus: contactStatus,
                        }, // 返回用户信息
                    })
                }
            },
        )
    })
}

// 申请好友
exports.applyFriend = (req, res) => {
    const applyForm = req.body

    let isHasFriend = true

    const applySql = `SELECT userId1, userId2 FROM friendships WHERE userId1 = ?`

    db.query(applySql, [applyForm.smallId], (err, results) => {
        if (err) {
            return res.cc(err) // 使用 res.cc 方法返回错误信息
        }

        if (results.length > 0) {
            for (let i = 0; i < results.length; i++) {
                if (results[i].userId2 === applyForm.bigId) {
                    const updateSql = `UPDATE friendships SET status = 'verifying', initiator = ? WHERE
                    (userId1 = ? AND userId2 = ?)`

                    db.query(
                        updateSql,
                        [applyForm.initiator, applyForm.smallId, applyForm.bigId],
                        (err, _result) => {
                            if (err) {
                                return res.cc(err) // 使用 res.cc 方法返回错误信息
                            }

                            return res.send({
                                code: 200,
                                message: '好友申请成功',
                            })
                        },
                    )
                    return
                }
            }
            console.log('aaaaa')
            isHasFriend = false
        }

        if (results.length === 0 || !isHasFriend) {
            const addSql = `Insert into friendships SET ?`

            db.query(
                addSql,
                {
                    userId1: applyForm.smallId,
                    userId2: applyForm.bigId,
                    initiator: applyForm.initiator,
                    createTime: applyForm.createTime,
                },
                (err, _result) => {
                    if (err) {
                        return res.cc(err) // 使用 res.cc 方法返回错误信息
                    }

                    res.send({
                        code: 200,
                        message: '好友申请成功',
                    })
                },
            )
        }
    })
}
